package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gorilla/websocket"
)

func main() {
	// 创建WebSocket连接
	u := "ws://127.0.0.1:8808/chat"
	log.Printf("连接到 %s", u)
	c, _, err := websocket.DefaultDialer.Dial(u, nil)
	if err != nil {
		log.Fatal("连接错误：", err)
	}
	defer c.Close()

	// 处理中断信号
	interrupt := make(chan os.Signal, 1)
	signal.Notify(interrupt, syscall.SIGINT, syscall.SIGTERM)

	// 启动协程接收消息
	go func() {
		for {
			_, message, err := c.ReadMessage()
			if err != nil {
				log.Println("读取消息错误：", err)
				break
			}
			fmt.Println("WebSocket服务 Get message:", string(message))
		}
	}()

	// 等待中断信号
	<-interrupt
	log.Println("接收到中断信号，关闭连接")
	err = c.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
	if err != nil {
		log.Println("关闭连接错误：", err)
	}
	time.Sleep(time.Second)
}
